<?php

namespace app\common\model;

use app\admin\model\Admin;
use ba\Random;
use think\Exception;
use think\facade\Db;
use think\Model;

/**
 * Staff
 */
class Staff extends Model
{
    // 表名
    protected $name = 'staff';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;


    public function store(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(\app\admin\model\Store::class, 'store_id', 'id');
    }

    public function admin(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(\app\admin\model\Admin::class, 'admin_id', 'id');
    }

    public static function onBeforeInsert(Model $model) {
        $res = Admin::where([
            ['mobile', '=', $model->phone]
        ])->findOrEmpty();
        if(!$res->isEmpty()) {
            throw new Exception('联系手机已存在!');
            return false;
        }
    }

    public static function onAfterInsert(Model $model): void
    {
        $salt   = Random::build('alnum', 16);
        $passwd = encrypt_password('123456', $salt);
        $time = time();
        $admin = [
            'username'=> $model->phone,
            'nickname'=> $model->staff_name,
            'mobile'=> $model->phone,
            'password'=> $passwd,
            'salt'=> $salt,
            'createtime'=> $time,
            'updatetime'=> $time,
            'status'=> 1
        ];

        $adminModel = Admin::create($admin);
        $model->admin_id = $adminModel->id;
        $model->save();
        Db::name('admin_group_access')->insert([
            'uid'=> $adminModel->id,
            'group_id'=> 5
        ]);
    }

    public static function onAfterDelete(Model $model): void
    {
        Admin::destroy($model->admin_id);
    }
}